from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

from myapp.models import User

from django.utils.deprecation import MiddlewareMixin

from django.http import QueryDict


#类视图调用
from django.utils.decorators import method_decorator

#事务操作
from django.db import transaction

from redis import StrictRedis
import datetime

#定义验证码类
class MyCode(View):

	#内置类方法
	def get_random_color(self):

		R=random.randrange(255)
		G=random.randrange(255)
		B=random.randrange(255)

		return (R,G,B)

	def get(self,request):

		#定义画布
		img_size=(120,50)

		#定义图像对象
		image=Image.new('RGB',img_size,'white')
		#定义画笔
		draw=ImageDraw.Draw(image,'RGB')
		#定义字符串
		source='0123456789abcdefg'
		#定义容器
		code_str=''
		for i in range(4):
			#获取字符颜色
			text_color=self.get_random_color()
			#获取随机字符
			tmp_num=random.randrange(len(source))
			random_str=source[tmp_num]
			code_str+=random_str
			draw.text((10+30*i,20),random_str,text_color)

		buf=io.BytesIO()
		image.save(buf,'png')

		#保存验证码
		# request.session['code']=code_str

		sr = StrictRedis()
		sr.set('code',code_str)  # 将cpf值设置为name变量
		return HttpResponse(buf.getvalue(),'image/png')

				#打开radis客户端


#md5加密
def make_password(mypass):

    #生成对象
    md5=hashlib.md5()
    #定义加密对象
    sign_str=mypass
    #转码
    sign_utf8=str(sign_str).encode(encoding='utf-8')
    #加密
    md5.update(sign_utf8)
    #生成密文
    md5_server=md5.hexdigest()

    return md5_server

#登录接口
class Login(APIView):
	def post(self,request):
		username=request.POST.get('username',None)
		phone=request.POST.get('phone',None)
		password=request.POST.get('password',None)
		code=request.POST.get('code',None)

		# 获取验证码
		sr = StrictRedis()
		img_code=sr.get('code').decode()  # 返回值为b'cpf'

		if code != img_code:
			return Response({'code':406,'message':'图片验证错误'})

		#判断
		if username:
			user = User.objects.filter(username=username, password=make_password(password)).first()
		else:
			user = User.objects.filter(phone=phone, password=password).first()
		if user:
			encode_jwt=jwt.encode({'uid':user.id,'username':user.username},'123',algorithm='HS256')
			encode_str=str(encode_jwt,'utf-8')
			return Response({'code':200,'message':'登录成功','username':user.username,'token':encode_str})
		else:
			return Response({'code':405,'message':'您的用户名或者密码错误'})
	def put(self,request):

		password=request.POST.get('password',None)
		token=request.POST.get('token',None)
		# 解密
		decode_jwt = jwt.decode(token, '123', algorithms=['HS256'])
		User.objects.filter(username=decode_jwt['username']).update(password=make_password(password))
		return Response({'code':200,'msg':'密码修改成功'})

#用户注册
class Register(APIView):
	def post(self,requests):
		#接收参数
		username=requests.POST.get('username',None)
		password=requests.POST.get('password',None)
		phone=requests.POST.get('phone',None)

		#排重
		user=User.objects.filter(username=username).first()#.get(username=username)
		print(phone)
		if user:
			res={}
			res['code']=405
			res['message']='用户已经存在'

			return Response(res)

		#入库 捕获异常
		try:
			user=User(username=username,password=make_password(password),phone=phone)
			user.save()
			return Response({'code':200,'message':'注册成功'})
		except Exception as e:

			return Response({'code':200,'message':'用户已存在'})








